package com.rykj.widget;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

import com.rykj.R;
import com.rykj.util.LogX;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import androidx.appcompat.app.AlertDialog;

/**
 * Description: author: zhangsan on 2017/6/16 下午1:49.
 */

public class WebViewCommon extends FrameLayout {

    private static final String TAG = "WebViewCommon";

    private WebView webview;

    private ProgressBar progressbar;

    private RYEmptyView mEmptyView;

    private boolean isFirst = true;

    private boolean notError = true;
    private IWebViewClient mIWebViewClient;
    private MyWebChromeClient mWebChromeClient;
    private OverrideUrlWebViewClient mWebViewClient;

    /**
     *
     */
    public WebViewCommon(Context context, AttributeSet attrs) {
        super(context, attrs);
        initLayout(context);
    }

    private void initLayout(Context context) {
        setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        inflate(context, R.layout.layout_webview_common, this);
        webview = (WebView) findViewById(R.id.webview);
        progressbar = (ProgressBar) findViewById(R.id.progressbar);
        mEmptyView = (RYEmptyView) findViewById(R.id.emptyview);

        mEmptyView.bind(webview);

        initWebViewSettings();
        WebView.setWebContentsDebuggingEnabled(true);

        mWebViewClient = new OverrideUrlWebViewClient();
        webview.setWebViewClient(mWebViewClient);
        mWebChromeClient = new MyWebChromeClient();
        webview.setWebChromeClient(mWebChromeClient);
    }

    /**
     * init WebView Settings
     */
    private void initWebViewSettings() {
        // 设置可以访问文件
        webview.getSettings().setAllowFileAccess(true);
        //如果访问的页面中有Javascript，则webview必须设置支持Javascript
        webview.getSettings().setJavaScriptEnabled(true);
//        webview.getSettings().setUserAgentString(App.getInstance().getUserAgent());
        webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        webview.getSettings().setAllowFileAccess(true);
        webview.getSettings().setAppCacheEnabled(true);
        webview.getSettings().setDomStorageEnabled(true);
        webview.getSettings().setDatabaseEnabled(true);

        // 自适应屏幕
        webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
//        webview.getSettings().setLoadWithOverviewMode(true);
//        webview.getSettings().setUseWideViewPort(true);

    }

    public boolean isNotError() {
        return notError;
    }

    public void setNotError(boolean notError) {
        this.notError = notError;
    }

    public void loadData(String s) {
        //  加载、并显示HTML代码
        webview.loadDataWithBaseURL(null, s, "text/html", "utf-8", null);
    }

    public void setIWebViewClient(IWebViewClient IWebViewClient) {
        mIWebViewClient = IWebViewClient;
    }

    public MyWebChromeClient getWebChromeClient() {
        return mWebChromeClient;
    }

    /**
     *
     */
    public void setWebChromeClient(MyWebChromeClient webChromeClient) {
        mWebChromeClient = webChromeClient;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

    }

    public void loadUrl(String url) {
        LogX.d(TAG, "loadUrl: " + url);
        webview.loadUrl(url);
    }

    public void reload() {
        webview.reload();
    }

    public WebView getWebview() {
        return webview;
    }

    public void destroy() {
        removeAllViews();
        if (webview != null) {
            webview.destroy();
        }
    }

    public interface IWebViewClient {
        void onPageFinished();
    }

    public interface OpenFileChooserCallBack {
        void openFileChooserCallBack(ValueCallback<Uri> uploadMsg, String acceptType);

        void showFileChooserCallBack(ValueCallback<Uri[]> filePathCallback);
    }

    public class MyWebChromeClient extends WebChromeClient {

        private OpenFileChooserCallBack mOpenFileChooserCallBack;

        public void setOpenFileChooserCallBack(OpenFileChooserCallBack openFileChooserCallBack) {
            mOpenFileChooserCallBack = openFileChooserCallBack;
        }

        @Override
        public boolean onJsAlert(WebView webView, String s, String s1, final JsResult jsResult) {
            LogX.d(TAG,
                    "onJsAlert() called with: s = [" + s + "], s1 = [" + s1 + "], jsResult = [" + jsResult + "]");
            final AlertDialog dlg = new AlertDialog.Builder(getContext()).setTitle(null)
                    .setMessage(s1).setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            jsResult.confirm();
                        }
                    }).create();
            dlg.show();
            dlg.setOnDismissListener(new DialogInterface.OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog) {
                    jsResult.cancel();
                }
            });
            return true;
        }

        @Override
        public boolean onJsConfirm(WebView webView, String s, String s1, final JsResult jsResult) {
            LogX.d(TAG,
                    "onJsConfirm() called with: s = [" + s + "], s1 = [" + s1 + "], jsResult = [" + jsResult + "]");
            final AlertDialog dlg = new AlertDialog.Builder(getContext()).setTitle(null)
                    .setMessage(s1).setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            jsResult.confirm();
                        }
                    }).create();
            dlg.show();
            dlg.setOnDismissListener(new DialogInterface.OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog) {
                    jsResult.cancel();
                }
            });
            return true;
        }

        @Override
        public void onProgressChanged(WebView webView, int progress) {
            LogX.d(TAG, "progress = " + progress);
            progressbar.setProgress(progress);
            if (isFirst) {
                if (progress >= 90) {
                    isFirst = false;
                    mEmptyView.loadSuccuss();
                } else {
                    mEmptyView.showLoading();
                }
            }
        }

        // For Android  > 4.1.1
        @Override
        public void openFileChooser(ValueCallback<Uri> uploadMsg,
                String acceptType,
                String capture) {
            mOpenFileChooserCallBack.openFileChooserCallBack(uploadMsg, acceptType);
        }

        // For Android 5.0+
        @Override
        public boolean onShowFileChooser(WebView webView,
                ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {
            mOpenFileChooserCallBack.showFileChooserCallBack(filePathCallback);
            return true;
        }
    }

    public class OverrideUrlWebViewClient extends WebViewClient {

        /**
         * 当前打开的页面链接
         */
        private String willPageUrl = "";

        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String url) {
            LogX.d(TAG,
                    "shouldOverrideUrlLoading() called with: webView = [" + webView + "], s = [" + url + "]");
            // 获取上下文, H5PayDemoActivity为当前页面
            final Context context = WebViewCommon.this.getContext();

            // ------  对alipays:相关的scheme处理 -------
            if (url.startsWith("alipays:") || url.startsWith("alipay")) {
                try {
                    context.startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                    ((Activity) context).finish();
                } catch (Exception e) {
                    new AlertDialog.Builder(context).setMessage("未检测到支付宝客户端，请安装后重试。")
                            .setPositiveButton("立即安装", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Uri alipayUrl = Uri.parse("https://d.alipay.com");
                                    context.startActivity(new Intent("android.intent.action.VIEW",
                                            alipayUrl));
                                }
                            }).setNegativeButton("取消", null).show();
                }
                //((Activity) context).finish();
                return true;
            }
            // ------- 处理结束 -------

            if (!(url.startsWith("http") || url.startsWith("https"))) {
                return true;
            }
            loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
            LogX.d(TAG, "onPageStarted() called with: s = [" + s + "], bitmap = [" + bitmap + "]");
            super.onPageStarted(webView, s, bitmap);
            // 设置当前打开的页面链接
            willPageUrl = s;
        }

        @Override
        public void onPageFinished(WebView webView, String s) {
            LogX.d(TAG, "onPageFinished() called with:  s = [" + s + "]");
            super.onPageFinished(webView, s);
            progressbar.setVisibility(GONE);
            if (mIWebViewClient != null) {
                mIWebViewClient.onPageFinished();
            }
        }

        @Override
        public void onReceivedError(WebView webView, int i, String s, String s1) {
            LogX.e(TAG,
                    "onReceivedError() called with:  i = [" + i + "], s = [" + s + "], s1 = [" + s1 + "]");
            super.onReceivedError(webView, i, s, s1);
            notError = false;
        }


        @Override
        public void onReceivedHttpError(WebView webView,
                WebResourceRequest webResourceRequest,
                WebResourceResponse webResourceResponse) {
            super.onReceivedHttpError(webView, webResourceRequest, webResourceResponse);
            String webRequestUrl = webResourceRequest.getUrl().toString();
            if (willPageUrl.equals(webRequestUrl)) {    // 是当前访问地址报错
                // 显示页面出错
                LogX.d(TAG, String.format("页面出错 错误码 %s", webResourceResponse.getStatusCode()));
//                CommonUtil.showToast("显示页面出错");

            } else { //  适当前访问地址的资源文件报错
                LogX.d(TAG, String.format("页面资源文件出错 错误码 %s", webResourceResponse.getStatusCode()));
//                CommonUtil.showToast("显示页面资源出错");
            }

        }

    }
}
